import React from 'react';
import {Linking, Text, View} from 'react-native';
import {Button, Card, ListView, WhiteSpace, WingBlank} from '@ant-design/react-native';
import data from './json';

function group(array, subGroupLength) {
  var index = 0;
  var newArray = [];

  while (index < array.length) {
    newArray.push(array.slice(index, (index += subGroupLength)));
  }
  return newArray;
}

const dataMapList = group(data.data, 10);

export default class CardList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      layout: 'list',
    };
  }

  sleep = (time: any) =>
    new Promise(resolve => setTimeout(() => resolve(), time));

  //默认的加载方法
  onFetch = async (page = 1, startFetch, abortFetch) => {
    console.log(dataMapList);
    try {
      let pageLimit = 10;
      if (this.state.layout === 'grid') {
        pageLimit = 60;
      }
      const skip = (page - 1) * pageLimit;

      //Generate dummy data
      let rowData = Array.from(
        {length: pageLimit},
        (_, index) => `item -> ${index + skip}`,
      );

      //Simulate the end of the list if there is no more data returned from the server
      if (page === 3) {
        rowData = [];
      }

      //Simulate the network loading in ES7 syntax (async/await)
      await this.sleep(2000);
      startFetch(rowData, pageLimit);
    } catch (err) {
      abortFetch(); //manually stop the refresh or pagination if it encounters network error
    }
  };
  timestampTomStr = timestamp => {
    let date = new Date(timestamp);
    let Y = date.getFullYear() + '-';
    let M =
      (date.getMonth() + 1 < 10
        ? '0' + (date.getMonth() + 1)
        : date.getMonth() + 1) + '-';
    let D = date.getDate() + ' ';
    let h = date.getHours() + ':';
    let m = date.getMinutes() + ':';
    let s = date.getSeconds();
    return Y + M + D + h + m + s;
  };

  onFetch1 = (page = 1, startFetch, abortFetch) => {
    try {
      let pageLimit = 10;
      const rowData = dataMapList[page];
      startFetch(rowData, pageLimit);
    } catch (err) {
      abortFetch(); //manually stop the refresh or pagination if it encounters network error
    }
  };

  renderItem = item => {
    return (
      <>
        <WingBlank size="lg">
          <Card>
            <Card.Header
              title={item.pubDateStr}
              thumbStyle={{width: 30, height: 30}}
              thumb="https://gw.alipayobjects.com/zos/rmsportal/MRhHctKOineMbKAZslML.jpg"
              extra={item.provinceName}
            />
            <Card.Body>
              <View>
                <Text style={{marginLeft: 16}}>{item.summary}</Text>

                <WingBlank
                  style={{
                    marginTop: 20,
                    flexDirection: 'row',
                    justifyContent: 'flex-end',
                    // alignItems: 'end',
                  }}>
                  <Button
                    type="ghost"
                    size="small"
                    onPress={() => {
                      Linking.openURL(item.sourceUrl);
                    }}>
                    查看详情
                  </Button>
                </WingBlank>
              </View>
            </Card.Body>
            <Card.Footer
              content={'消息来源：' + item.infoSource}
              extra={this.timestampTomStr(item.pubDate)}
            />
          </Card>
        </WingBlank>
        <WhiteSpace size="sm"/>
      </>
    );
  };

  render() {
    return (
      <ListView
        onFetch={this.onFetch1}
        keyExtractor={(item, index) =>
          `${this.state.layout}  ${item} - ${index}`
        }
        renderItem={this.renderItem}
        numColumns={this.state.layout === 'list' ? 1 : 3}
      />
    );
  }
}
